/**
 * 
 */
package edu.fzu.shop.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.fzu.shop.exception.DataAccessException;



/**
 * @author ctd
 *
 */
public class DBUtil {
	private static final String CONN_STR="jdbc:oracle:thin:@localhost:1521:orcl";
	private static final String USERNAME="onlineshop";
	private static final String PWD="abc123";

	//用来把Connection绑定到当前线程上的变�?
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();	
	
	private static DBUtil me=new DBUtil();
	
	private DBUtil() {}
	
	public static DBUtil getInstance()
	{
		return me;
	}
	
	//�?个静态块在该类被加载的时候，自动运行�?次，然后将不再运行�??
	static {
		try {			

			//查看类路径中是否存在这个驱动入口�?
			//Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");	
			
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {			
			e.printStackTrace();
		}		
	}
	
	/**
	 * 获取数据库连�?
	 * @return
	 */
	public static synchronized Connection getConn()
	{
		
		//先从当前线程上取出连接实�?
		Connection conn = tl.get();	
		
		//如果当前线程上没有Connection的实�? 
		if(null == conn){ 				
			try {
				//从连接池中取出一个连接实�? 
				//conn = DriverManager.getConnection("proxool.hotelsys-ds");
				
				conn=DriverManager.getConnection(CONN_STR, USERNAME, PWD);
				//把它绑定到当前线程上
				tl.set(conn); 
			} catch (SQLException e) {					
				throw new DataAccessException("获取连接时异常?",e);
			}
		
		}
		
			
		return conn;
		
	}
	
	/**
	 * 释放数据库资�?
	 * @param conn
	 * @param pstmt
	 * @param rset
	 */
	public void releaseConn(Connection conn){
		if(conn!=null)  {
			tl.remove(); //释放该线程上的连接绑定器
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void ReleaseRes(Connection conn,PreparedStatement pstmt,ResultSet rset)
	{
		try{
		  if(rset!=null) rset.close();
		  if(pstmt!=null) pstmt.close();
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
	}
	
	public static synchronized TransactionManager getTranManager(){
		return new TransactionManager();
	}
	

}
